package smetana.modules.business;

import smetana.domain.raw.*;
import smetana.mapper.raw.PositionGroupMapper;
import smetana.mapper.raw.PositionMapper;
import smetana.mapper.raw.PositionTypeMapper;
import smetana.mapper.raw.PositionUnitMapper;
import smetana.modules.business.meta.Commit;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dmitry.mamonov
 */
class BusinessPositionImpl extends BaseImpl implements BusinessPosition {
    @Override
    public Position findPositionById(Integer id) {
        if (id == null) {
            return null;
        } else {
            PositionMapper productMapper = sql.getMapper(PositionMapper.class);
            Position product = productMapper.findById(id);
            return product;
        }
    }
    @Override
    public Map<Integer, PositionGroup> loadProductGroupsMap() {
        Map<Integer, PositionGroup> result = new HashMap<Integer, PositionGroup>();
        PositionGroupMapper productGroupMapper = sql.getMapper(PositionGroupMapper.class);
        for (PositionGroup pg : productGroupMapper.listAll()) {
            result.put(pg.getId(), pg);
        }
        return result;
    }

    @Override
    public Map<Integer, Position> loadProductsMap() {
        Map<Integer, Position> result = new HashMap<Integer, Position>();
        PositionMapper mapper = sql.getMapper(PositionMapper.class);
        for (Position p : mapper.listAll()) {
            result.put(p.getId(), p);
        }
        return result;
    }

    @Override
    public Position newPositionUnsaved() {
        PositionMapper mapper = sql.getMapper(PositionMapper.class);
        Position position = new Position(mapper.nextId());
        return position;
    }

    @Override
    @Commit
    public Position newPosition(Position position){
        PositionMapper mapper = sql.getMapper(PositionMapper.class);
        mapper.insert(position);
        return mapper.findById(position.getId());
    }

    @Override
    public List<PositionType> listPositionTypes() {
        PositionTypeMapper mapper = sql.getMapper(PositionTypeMapper.class);
        return mapper.listAll();
    }

    @Override
    public List<PositionUnit> listPositionUnits() {
        PositionUnitMapper mapper = sql.getMapper(PositionUnitMapper.class);
        return mapper.listAll();
    }
}
